#!/bin/bash

# QEMU K8s虚拟机创建脚本
# 用法: ./create-vm.sh <vm_name> <vm_type> <ip_address>
# vm_type: master 或 worker

set -e

# 加载配置文件
SOURCE_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SOURCE_DIR/config.conf"

# 参数检查
if [ $# -ne 3 ]; then
    echo "用法: $0 <vm_name> <vm_type> <ip_address>"
    echo "示例: $0 k8s-master1 master 192.168.100.10"
    exit 1
fi

VM_NAME="$1"
VM_TYPE="$2"
VM_IP="$3"

# 创建必要的目录
mkdir -p "$VM_IMAGE_DIR"
mkdir -p "$LOG_DIR"

# 虚拟机磁盘镜像路径
VM_DISK="$VM_IMAGE_DIR/${VM_NAME}.qcow2"
VM_LOG="$LOG_DIR/${VM_NAME}.log"

# 检查ISO文件是否存在
if [ ! -f "$ISO_PATH" ]; then
    echo "错误: ISO文件不存在: $ISO_PATH"
    exit 1
fi

# 检查虚拟机是否已存在
if [ -f "$VM_DISK" ]; then
    echo "警告: 虚拟机磁盘已存在: $VM_DISK"
    read -p "是否覆盖? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "取消创建虚拟机"
        exit 1
    fi
    rm -f "$VM_DISK"
fi

# 创建虚拟机磁盘
echo "创建虚拟机磁盘: $VM_DISK"
qemu-img create -f qcow2 "$VM_DISK" "$VM_DISK_SIZE"

# 生成MAC地址
generate_mac() {
    printf '52:54:00:%02x:%02x:%02x\n' $((RANDOM%256)) $((RANDOM%256)) $((RANDOM%256))
}

VM_MAC=$(generate_mac)

# 计算端口号
VM_INDEX=$(echo "$VM_IP" | cut -d'.' -f4)
VNC_PORT=$((VNC_PORT_START + VM_INDEX - 10))
SSH_PORT=$((SSH_PORT_START + VM_INDEX - 10))

# 创建虚拟机启动脚本
START_SCRIPT="$VM_IMAGE_DIR/start-${VM_NAME}.sh"
cat > "$START_SCRIPT" << EOF
#!/bin/bash

# 启动虚拟机: $VM_NAME
# IP地址: $VM_IP
# 类型: $VM_TYPE

set -e

# 检查网桥是否存在
if ! ip link show "$BRIDGE_NAME" >/dev/null 2>&1; then
    echo "错误: 网桥 $BRIDGE_NAME 不存在，请先运行网络配置脚本"
    exit 1
fi

echo "启动虚拟机: $VM_NAME"
echo "VNC端口: $VNC_PORT"
echo "SSH端口: $SSH_PORT"
echo "IP地址: $VM_IP"

$QEMU_SYSTEM \\
    -name "$VM_NAME" \\
    -machine type=pc,accel=kvm \\
    -cpu host \\
    -smp "$VM_VCPUS" \\
    -m "$VM_MEMORY" \\
    -drive file="$VM_DISK",format=qcow2,if=virtio \\
    -netdev bridge,id=net0,br="$BRIDGE_NAME" \\
    -device virtio-net-pci,netdev=net0,mac="$VM_MAC" \\
    -vnc ":$((VNC_PORT - 5900))" \\
    -monitor unix:"$VM_IMAGE_DIR/${VM_NAME}.monitor",server,nowait \\
    -pidfile "$VM_IMAGE_DIR/${VM_NAME}.pid" \\
    -daemonize \\
    -boot order=cd \\
    >> "$VM_LOG" 2>&1

echo "虚拟机 $VM_NAME 已启动"
echo "VNC连接: localhost:$VNC_PORT"
echo "监控文件: $VM_IMAGE_DIR/${VM_NAME}.monitor"
echo "PID文件: $VM_IMAGE_DIR/${VM_NAME}.pid"
echo "日志文件: $VM_LOG"
EOF

chmod +x "$START_SCRIPT"

# 创建首次安装启动脚本（带ISO）
INSTALL_SCRIPT="$VM_IMAGE_DIR/install-${VM_NAME}.sh"
cat > "$INSTALL_SCRIPT" << EOF
#!/bin/bash

# 安装虚拟机: $VM_NAME
# 首次启动，挂载ISO进行系统安装

set -e

# 检查网桥是否存在
if ! ip link show "$BRIDGE_NAME" >/dev/null 2>&1; then
    echo "错误: 网桥 $BRIDGE_NAME 不存在，请先运行网络配置脚本"
    exit 1
fi

echo "开始安装虚拟机: $VM_NAME"
echo "VNC端口: $VNC_PORT (用于安装界面)"
echo "IP地址: $VM_IP"
echo "请通过VNC连接进行系统安装"

$QEMU_SYSTEM \\
    -name "$VM_NAME" \\
    -machine type=pc,accel=kvm \\
    -cpu host \\
    -smp "$VM_VCPUS" \\
    -m "$VM_MEMORY" \\
    -drive file="$VM_DISK",format=qcow2,if=virtio \\
    -drive file="$ISO_PATH",media=cdrom,readonly \\
    -netdev bridge,id=net0,br="$BRIDGE_NAME" \\
    -device virtio-net-pci,netdev=net0,mac="$VM_MAC" \\
    -vnc ":$((VNC_PORT - 5900))" \\
    -monitor unix:"$VM_IMAGE_DIR/${VM_NAME}.monitor",server,nowait \\
    -pidfile "$VM_IMAGE_DIR/${VM_NAME}.pid" \\
    -boot order=cd \\
    >> "$VM_LOG" 2>&1

echo "虚拟机 $VM_NAME 安装模式已启动"
echo "VNC连接: localhost:$VNC_PORT"
echo "请通过VNC客户端连接进行CentOS安装"
echo "安装完成后，使用 $START_SCRIPT 启动虚拟机"
EOF

chmod +x "$INSTALL_SCRIPT"

# 创建虚拟机信息文件
VM_INFO="$VM_IMAGE_DIR/${VM_NAME}.info"
cat > "$VM_INFO" << EOF
# 虚拟机信息: $VM_NAME
VM_NAME=$VM_NAME
VM_TYPE=$VM_TYPE
VM_IP=$VM_IP
VM_MAC=$VM_MAC
VNC_PORT=$VNC_PORT
SSH_PORT=$SSH_PORT
VM_DISK=$VM_DISK
START_SCRIPT=$START_SCRIPT
INSTALL_SCRIPT=$INSTALL_SCRIPT
CREATED_TIME=$(date '+%Y-%m-%d %H:%M:%S')
EOF

echo "虚拟机创建完成!"
echo "虚拟机名称: $VM_NAME"
echo "虚拟机类型: $VM_TYPE"
echo "IP地址: $VM_IP"
echo "MAC地址: $VM_MAC"
echo "VNC端口: $VNC_PORT"
echo "磁盘文件: $VM_DISK"
echo "安装脚本: $INSTALL_SCRIPT"
echo "启动脚本: $START_SCRIPT"
echo "信息文件: $VM_INFO"
echo ""
echo "下一步:"
echo "1. 运行网络配置: ./setup-network.sh"
echo "2. 启动安装: $INSTALL_SCRIPT"
echo "3. 通过VNC (localhost:$VNC_PORT) 完成系统安装"
echo "4. 安装完成后使用: $START_SCRIPT"